const {
    getList,
    getDetail,
    newBlog,
    updataBlog,
    deleteBlog } = require('../controller/blog')
const { SuccessModel, ErrnoModel } = require('../model/resModel')
const handleBlogRouter = (req, res) => {
    const method = req.method
    let blogId = req.query.id || ''



    //登录验证
    const loginCheck = () => {
        if (!req.session.username) {
            return Promise.resolve(
                new ErrnoModel('未登录')
            )
        }
    }
    //获取blog列表
    if (method === 'GET' && req.path === '/api/blog/list') {
        let author = req.query.author || ''
        let keyword = req.query.keyword || ''
        // let listData = getList(author, keyword)
        // return new SuccessModel(listData)
        const result = getList(author, keyword)
        return result.then(listData => {
            return new SuccessModel(listData)
        })
    }
    //获取bolg详情页
    if (method === 'GET' && req.path === '/api/blog/detail') {
        // let detailData = getDetail(blogId)
        // return new SuccessModel(detailData)
        const result = getDetail(blogId)
        return result.then(detailData => {
            return new SuccessModel(detailData)
        })
    }
    //新建一篇博客
    if (method === 'POST' && req.path === '/api/blog/new') {

        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            //未登录
            return loginCheckResult
        }
        req.body.author = req.session.username
        const result = newBlog(req.body)
        return result.then(data => {
            if (!data) {
                return new ErrnoModel('新建博客失败！')
            }
            return new SuccessModel(data)
        })
    }

    //更新一篇博客
    if (method === 'POST' && req.path === '/api/blog/update') {
        // const result = updataBlog(blogId, req.body)
        // if (result) return new SuccessModel(result)
        // else return new ErrnoModel('更新博客失败！')
        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            //未登录
            return loginCheckResult
        }
        const result = updataBlog(blogId, req.body)
        return result.then(data => {
            if (!data) {
                return new ErrnoModel('更新博客失败！')
            }
            return new SuccessModel()
        })
    }
    //删除一篇博客
    if (method === 'POST' && req.path === '/api/blog/del') {


        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            //未登录
            return loginCheckResult
        }

        req.body.author = req.session.username
        const result = deleteBlog(blogId, author)

        return result.then(data => {
            if (!data) {
                return new ErrnoModel('删除失败！')
            }
            return new SuccessModel()
        })
    }
}
module.exports = handleBlogRouter